<template>
  <div>
    <div>
      <el-dialog
        title="选择任务模板"
        width="40%"
        :visible.sync=checkTask.dialog
        center>
        <div style="margin:auto 10px;height:100%;position:relative;">
          <div style="margin-bottom: 5px" v-role="'超级管理员'">
            <div>
              <span style="font-size: 15px;font-weight: bold;letter-spacing: 1px">执行环境 : </span>
              <el-radio-group v-model="checkTask.isTestExecute">
                <el-radio-button :label=false>线上</el-radio-button>
                <el-radio-button :label=true>测试</el-radio-button>
              </el-radio-group>
              <el-radio-group style="margin-left: 25px" v-model="lookMe">
                <el-radio :label=true>只看我自己</el-radio>
                <el-radio :label=false>查看所有人的模板</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div>
            <el-select
              @focus="getTaskTemplateList"
              style="margin: 5px 0;width: 100%"
              v-model=checkTask.sTaskTemplate
              value-key="id"
              loading-text="加载中...."
              :loading="templateLoading"
              placeholder="选择编辑好的任务模板"
              filterable
            >
              <el-option
                v-for="item in taskTemplateList"
                :key=item.id
                :label=item.name
                :value=item>
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">用户编号: {{ item.adId }}</span>
              </el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" style="width:20%" @click="pushTask()">提 交</el-button>
      </span>
      </el-dialog>
      <el-drawer
        size="90%"
        title="机器日志"
        :visible.sync="logDrawer.show"
        direction="ltr"
        :before-close="logDrawer.handleClose"
      >
        <div style="margin: 0 10px;background-color: #2d3436;padding: 5px;color: #ecf0f1">
          <p style="width: 100%;white-space: pre-line;">{{ logDrawer.txt }}</p>
        </div>
      </el-drawer>
      <push-task-dialog ref="pushTaskDialog" @refreshTb="getRobotList"/>
    </div>

    <el-card style="height: 85vh">
      <div slot="header" style="text-align:center">
        <span
          style="font-size: 25px;font-weight: bold;color: #576574;letter-spacing: 0.1em"
        >
          机器信息
          <i class="el-icon-monitor"></i>
        </span>

      </div>

      <div style="margin-bottom: 15px">
        <el-button
          @click="$refs.pushTaskDialog.open(selectRobotList.map(i => i.robotNumber))"
          type="primary"
          size="mini"
          :disabled="selectRobotList.length === 0"
          plain
        >
          发布任务
        </el-button>
      </div>

      <el-table
        :data="robotList"
        @selection-change="tableSelectChange"
        v-loading=tabLoading
        :height="'65vh'"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          align="center"
          prop="robotNumber"
          label="编号"
          width="180">
        </el-table-column>
        <el-table-column
          v-if="hasPermission('robot.list.pcInfo')"
          align="center"
          prop="robotIp"
          label="计算机 IP"
          width="180">
        </el-table-column>
        <el-table-column
          v-if="hasPermission('robot.list.pcInfo')"
          align="center"
          prop="flaskPort"
          label="端口"
          width="180">
        </el-table-column>
        <el-table-column
          v-if="hasPermission('robot.list.pcInfo')"
          align="center"
          prop="remoteCode"
          label="远程代码">
        </el-table-column>
        <el-table-column
          v-if="hasPermission('robot.list.pcInfo')"
          align="center"
          prop="remotePwd"
          label="远程密码">
        </el-table-column>
        <el-table-column
          align="center"
          label="机器状态"
        >
          <template slot-scope="scope">
            <span :style="style.status(scope.row.statusId)">{{ html.status(scope.row.statusId) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="任务名称(正在执行)"
        >
          <template slot-scope="scope">
            <span>{{ isNullToStr(scope.row.taskName, "-") }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-popconfirm
              v-permission="'robot.list.stopTask'"
              v-if="scope.row.statusId === 2"
              @confirm="stopTask(scope.row.robotNumber)"
              confirm-button-text="好的"
              cancel-button-text="不用了"
              icon="el-icon-info"
              icon-color="red"
              title="确定打断这台机器正在执行的任务吗？"
            >
              <el-button
                style="margin: 3px"
                slot="reference"
                plain
                size="mini"
                type="danger"
              >
                结束任务
              </el-button>
            </el-popconfirm>
            <el-button
              v-permission="'robot.list.getLog'"
              style="margin: 3px"
              slot="reference"
              plain
              size="mini"
              type="primary"
              @click="getLog(scope.row.robotNumber)"
            >
              获取日志
            </el-button>
            <el-button
              v-permission="'robot.list.screenshot'"
              @click="getScreenshots(scope.row.robotNumber)"
              style="margin: 3px"
              slot="reference"
              plain
              size="mini"
              type="primary"
            >
              获取截图
            </el-button>
            <el-popconfirm
              v-permission="'robot.list.logOff'"
              @confirm="logout(scope.row.robotNumber)"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="机器即将停止正在执行的任务,并从后台中删除确认吗？"
            >
              <el-button
                style="margin: 3px"
                slot="reference"
                plain
                size="mini"
                type="danger"
              >
                注销机器
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>

<script>
import message from "@/utils/message";
import service, { isNullToStr, isNull } from "@/utils/service";
import imgUtils from "@/utils/imgUtils";
import MDViewer from "@/components/MDViewer.vue";
import { hasPermission } from "@/utils/auth";
import {list as getRobotTemplate} from "@/api/robot/robotTemplate"
import PushTaskDialog from "@/views/robotOffice/mod/pushTaskDialog.vue";

export default {
  name: "robotList",
  components: { PushTaskDialog, MDViewer },
  data() {
    let _vm = this;
    return {
      service: service,
      screenshotUrl: "",
      /* 任务执行方式 0 直接执行*/
      taskExecuteMethod: 0,
      /*机器列表*/
      robotList: [],
      /*选中机器列表*/
      selectRobotList: [],
      /*机器状态列表*/
      robotStatusList: [],
      /* 任务模板列表 */
      lookMe: true,
      templateLoading : false,
      taskTemplateList: [],
      /*表格加载相关*/
      tabLoading: true,
      style: {
        status(id) {
          let s = _vm.robotStatusList.find(t => {
            return id === t.id;
          });
          let result = {
            color: "#2f3542",
            fontSize: "17px",
            fontWeight: "bold",
            letterSpacing: "0.1em"
          };
          if (!isNull(s)) {
            result.color = s.fontColor;
          }
          return result;
        }
      },
      html: {
        status(id) {
          let s = _vm.robotStatusList.find(t => {
            return id === t.id;
          });
          if (!isNull(s)) {
            return s.name;
          } else {
            return "-";
          }
        }
      },
      /* 选择任务相关对象 */
      checkTask: {
        dialog: false,
        /* 选中的任务模板 */
        sTaskTemplate: {},
        /* 任务执行方式选项列表 */
        taskExecuteModeOptions: [],
        /* 任务开始执行日期 */
        taskExecuteDate: "",
        /* 任务循环执行间隔时间分钟 */
        taskCycleExecutionInterval: 0,
        /* 任务循环执行次数*/
        taskCycleCount: 0,
        /* 每日任务执行时间 */
        dailyTaskExecuteTime: "",
        /* 任务执行天数 */
        taskExecuteDays: 1,
        /* 是否测试执行 */
        isTestExecute: false,
        closeDrawer() {
          _vm.checkTask.taskExecuteDays = 1;
          _vm.checkTask.dailyTaskExecuteTime = "";
          _vm.checkTask.taskExecuteDate = "";
          _vm.checkTask.taskCycleExecutionInterval = 0;
          _vm.checkTask.taskCycleCount = 0;
          _vm.checkTask.sTaskTemplate = {};
          _vm.checkTask.dialog = false;
          _vm.checkTask.isTestExecute = false;
        },
        openDrawer() {
          if (_vm.selectRobotList.length === 0) {
            message.warning("请先选中执行任务的机器");
            return;
          }
          _vm.getRobotTaskExecuteModeList();
          _vm.checkTask.dialog = true;
        }
      },

      /* 日志抽屉 */
      logDrawer: {
        show: false,
        txt: "",
        handleClose() {
          _vm.logDrawer.show = false;
          _vm.logDrawer.txt = "";
        }
      }
    };
  },
  methods: {
    hasPermission,
    isNullToStr: isNullToStr,
    /*获取机器列表*/
    getRobotList() {
      let _t = this;
      _t.tabLoading = true;
      this.$request.post({
        url: "baseAdmin/robot/list",
        success: (res) => {
          _t.robotList = res;
        },
        error: () => {
          message.warning("机器信息获取失败");
        },
        finally: () => {
          _t.tabLoading = false;
        }
      });
    },

    /*获取机器状态列表*/
    getRobotStatusList() {
      let _t = this;
      this.$request.post({
        url: "baseAdmin/robot/statusList",
        success: (res) => {
          _t.robotStatusList = res;
        },
        error: () => {
          message.warning("获取机器状态列表失败");
        }
      });
    },

    /* 获取任务模板列表 */
    getTaskTemplateList() {
      this.templateLoading = true;
      getRobotTemplate(this.lookMe).then(r => {
        this.taskTemplateList = r.map(item => {
          return { id: item.id, adId: item.adId, name: item.name };
        });
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        this.templateLoading = false
      })
    },
    /* 表格选中改变 */
    tableSelectChange(v) {
      this.selectRobotList = v;
    },

    /* 跳转到模板界面 */
    gotoTaskTemplateView() {
      this.$router.push({
        path: "./taskTemplate/index"
      });
    },
    pushTaskParamCheck() {
      if (this.selectRobotList.length <= 0) {
        this.$message.warning("您还没有选择执行任务的机器");
        return false;
      }
      if (isNull(this.checkTask.sTaskTemplate.id)) {
        this.$message.warning("您还没有选择任务模板");
        return false;
      }
      return true;
    },

    /* 发布任务 */
    pushTask() {
      let _t = this;
      if (!_t.pushTaskParamCheck()) {
        return;
      }
      let robotIds = _t.selectRobotList.map(e => {
        return e.robotNumber;
      });
      let templateId = _t.checkTask.sTaskTemplate.id;
      let loading = this.$loading({
        lock: true,
        text: "提交中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$request.post({
        url: "baseAdmin/robot/pushTask",
        params: {
          robotIds: JSON.stringify(robotIds),
          templateId: templateId,
          taskExecuteDate: _t.checkTask.taskExecuteDate,
          taskCycleExecutionInterval: _t.checkTask.taskCycleExecutionInterval,
          taskCycleCount: _t.checkTask.taskCycleCount,
          dailyTaskExecuteTime: _t.checkTask.dailyTaskExecuteTime,
          taskExecuteDays: _t.checkTask.taskExecuteDays,
          isTestExecute: _t.checkTask.isTestExecute
        },
        success: (res) => {
          console.log("baseAdmin/robot/pushTask : ", res);
          message.success("发布任务成功");
        },
        finally: () => {
          _t.getRobotList();
          _t.checkTask.closeDrawer();
          loading.close();
        }
      });
    },

    /* 暂停任务 */
    stopTask(robotNumber) {
      let _t = this;
      let loading = this.$loading({
        lock: true,
        text: "提交中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$request.post({
        url: "baseAdmin/robot/stopTask",
        params: {
          robotNumber: robotNumber
        },
        success: (res) => {
          console.log("baseAdmin/robot/stopTask : ", res);
          message.success("操作成功");
        },
        finally: () => {
          _t.getRobotList();
          loading.close();
        }
      });
    },

    /* 获取机器日志 */
    getLog(robotNumber) {
      let _t = this;
      let loading = this.$loading({
        lock: true,
        text: "获取中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$request.post({
        url: "superAdmin/robot/getLog",
        params: {
          robotNumber: robotNumber
        },
        success: (res) => {
          // console.log("superAdmin/robot/getLog : ", res)
          for (let i = 0; i < res.length; i++) {
            if (res.charAt(i) === "\n") {
              console.log(123);
            }
          }
          _t.logDrawer.txt = res;
          _t.logDrawer.show = true;
        },
        finally: () => {
          _t.getRobotList();
          loading.close();
        }
      });
    },

    /* 获取截图 */
    getScreenshots(robotNumber) {
      let _t = this;
      this.$request.post({
        url: "superAdmin/robot/getScreenshots",
        params: {
          robotNumber: robotNumber
        },
        success: (res) => {
          _t.screenshotUrl = res;
          imgUtils.downloadImg(_t.screenshotUrl);
        }
      });
    },

    /* 注销机器 */
    logout(robotNumber) {
      let _t = this;
      let loading = this.$loading({
        lock: true,
        text: "申请中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      this.$request.post({
        url: "superAdmin/robot/logoutRobot",
        params: {
          robotNumber: robotNumber
        },
        success: (res) => {
          console.log("superAdmin/robot/logoutRobot : ", res);
          message.success("注销成功");
        },
        finally: () => {
          _t.getRobotList();
          loading.close();
        }
      });
    },

    /* 获取任务执行方式选项 */
    getRobotTaskExecuteModeList() {
      let _t = this;
      this.$request.post({
        url: "baseAdmin/robot/getRobotTaskExecuteModeList",
        success: res => {
          _t.checkTask.taskExecuteModeOptions = res;
          console.log("baseAdmin/robot/getRobotTaskExecuteModeList : ", res);
        }
      });
    }
  },
  mounted() {
    this.getRobotList();
    this.getRobotStatusList();
  }
};
</script>

<style scoped>
/deep/ .el-drawer__header {
  font-size: 25px !important;
  font-weight: bold !important;
  letter-spacing: 0.1em;
}

.drawer__footer {
  position: absolute;
  bottom: 5px;
  width: 100%;
}
</style>